package io.lkt.modules.sys.controller;

import com.google.common.collect.Lists;
import io.lkt.common.util.Query;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.modules.sys.entity.BUserInfoEntity;
import io.lkt.modules.sys.entity.BUserVipValidEntity;
import io.lkt.modules.sys.entity.SysUserEntity;
import io.lkt.modules.sys.service.BUserInfoService;
import io.lkt.modules.sys.service.BUserVipValidService;
import jodd.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author xss
 * @email dustwas@163.com
 * @date 2020-12-31 17:03:47
 */
@RestController
@RequestMapping("/sys/buservipvalid")
public class BUserVipValidController extends AbstractController {
    @Autowired
    private BUserVipValidService bUserVipValidService;

    @Autowired
    private BUserInfoService bUserInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list1")
//    @RequiresPermissions("sys:buservipvalid:list")
    public R list1(@RequestParam Map<String, Object> params) {
        System.out.println(params);
        Integer referType = 0;

        if (params.get("referType").toString().length() > 0) {
            referType = Integer.valueOf(params.get("referType").toString());
        }

        System.out.println(referType);

        PageUtils page = null;
        if (referType == 1) {
            // 大于等于30天
            page = bUserVipValidService.queryPageGe(params);
        } else if (referType == 2) {
            // 小于等于30天
            page = bUserVipValidService.queryPageLe(params);
        } else {
            page = bUserVipValidService.queryPage(params);
        }

        List<?> list = page.getList();

        if (CollectionUtils.isNotEmpty(list)) {
            List<BUserVipValidEntity> bUserVipValidList = Lists.newArrayList();

            for (Object temp : list) {
                BUserVipValidEntity bUserVipValid = (BUserVipValidEntity) temp;

                // 比较时间判断有没有过期
                String nowTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date());
                String endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(bUserVipValid.getEndTime());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                try {
                    Date date1 = format.parse(nowTime);
                    Date date2 = format.parse(endTime);

                    long beginMillisecond = date1.getTime();
                    long endMillisecond = date2.getTime();

                    if (beginMillisecond > endMillisecond) {
                        bUserVipValid.setVipStatus(0);
                    } else {
                        bUserVipValid.setVipStatus(1);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                // 用户基础信息
                if (bUserVipValid.getUserId() != null) {
//                    BUserInfoEntity bUserInfoEntity = this.bUserInfoService.getById(bUserVipValid.getUserId());
//
//                    if (bUserInfoService != null) {
//                        bUserVipValid.setNickName(Optional.ofNullable(bUserInfoEntity.getNickName()).orElse(""));
//                        bUserVipValid.setAvatarUrl(Optional.ofNullable(bUserInfoEntity.getAvatarUrl()).orElse(""));
//                    }

                    bUserVipValidList.add(bUserVipValid);
                }
            }
            page.setList(bUserVipValidList);
        }
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("sys:buservipvalid:list")
    public R list(@RequestParam Map<String, Object> params) throws ParseException {
        SysUserEntity curUser = getUser();
        params.put("curUserId", curUser.getUserId());

        //获取当前日期
        LocalDate date = LocalDate.now();
        LocalDate dateCut30 = date.plusDays(-15);
        LocalDate dateAdd30 = date.plusDays(15);

        Integer referType = 0;

        if (params.get("referType").toString().length() > 0) {
            referType = Integer.valueOf(params.get("referType").toString());
        }

        if (referType == 1) {
            params.put("startTime", date);
            params.put("endTime", dateAdd30);
        } else if (referType == 2) {
            params.put("startTime", dateCut30);
            params.put("endTime", date);
        } else {
            params.put("startTime", dateCut30);
            params.put("endTime", dateAdd30);
        }

        System.out.println(params);
        Query query = new Query(params);
        List<BUserVipValidEntity> list = bUserVipValidService.queryList(query);

        list = list.stream().map(info -> {
            String brandName = bUserVipValidService.queryBrandName(info.getUserId());

            if (StringUtil.isNotBlank(brandName)) {
                info.setBrandName(brandName);
            }

            try {
                int day = getTermDaysNum(info.getEndTime());
                if (compareNow(info.getEndTime()) < 0) {
                    info.setGendeStr("即将过期，剩" + day + "天");
                    if (day == 0) {
                        info.setGendeStr("即将过期");
                    }
                } else {
                    day = -day;
                    info.setGendeStr("已过期" + day + "天");
                    if (day == 0) {
                        info.setGendeStr("已过期");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return info;
        }).collect(Collectors.toList());

        Integer total = bUserVipValidService.queryTotal(query);
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    /**
     * 指定日期加上天数后的日期
     *
     * @param num     为增加的天数
     * @param newDate 创建时间
     * @return
     * @throws ParseException
     */
    public static String plusDay(int num, String newDate) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currdate = format.parse(newDate);
//        System.out.println("现在的日期是：" + currdate);
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        currdate = ca.getTime();
        String enddate = format.format(currdate);
//        System.out.println("增加天数以后的日期：" + enddate);
        return enddate;
    }

    private int getTermDaysNum(Date endTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date();
        Date date2 = endTime;

        String sdate1 = sdf.format(date1);
        String sdate2 = sdf.format(date2);

        date1 = sdf.parse(sdate1);
        date2 = sdf.parse(sdate2);

        long days = (date2.getTime() - date1.getTime()) / (24 * 3600 * 1000);

        return (int) days;
    }

    private int compareNow(Date endTime) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

        Date date1 = new Date();
        Date date2 = endTime;

        String time1 = simpleDateFormat.format(date1);
        String time2 = simpleDateFormat.format(date2);

        date1 = simpleDateFormat.parse(time1);
        date2 = simpleDateFormat.parse(time2);

        // 使用Date的compareTo()方法，大于、等于、小于分别返回1、0、-1
        return (int) date1.compareTo(date2);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
//    @RequiresPermissions("sys:buservipvalid:info")
    public R info(@PathVariable("userId") Integer userId) {
        BUserVipValidEntity bUserVipValid = bUserVipValidService.getById(userId);

        String nowTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date());
        String endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(bUserVipValid.getEndTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date date1 = format.parse(nowTime);
            Date date2 = format.parse(endTime);

            long beginMillisecond = date1.getTime();
            long endMillisecond = date2.getTime();

            if (beginMillisecond > endMillisecond) {
                bUserVipValid.setVipStatus(0);
            } else {
                bUserVipValid.setVipStatus(1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        BUserInfoEntity bUserInfoEntity = this.bUserInfoService.getById(userId);

        if (bUserInfoService != null) {
            bUserVipValid.setNickName(Optional.ofNullable(bUserInfoEntity.getNickName()).orElse(""));
            bUserVipValid.setAvatarUrl(Optional.ofNullable(bUserInfoEntity.getAvatarUrl()).orElse(""));
        }

        return R.ok().put("bUserVipValid", bUserVipValid);
    }

    /**
     * 保存
     */
//    @RequestMapping("/save")
////    @RequiresPermissions("sys:buservipvalid:save")
//    public R save(@RequestBody BUserVipValidEntity bUserVipValid) {
//        bUserVipValidService.save(bUserVipValid);
//
//        return R.ok();
//    }

    /**
     * 修改
     */
//    @RequestMapping("/update")
////    @RequiresPermissions("sys:buservipvalid:update")
//    public R update(@RequestBody BUserVipValidEntity bUserVipValid) {
//        ValidatorUtils.validateEntity(bUserVipValid);
//        bUserVipValidService.updateById(bUserVipValid);
//
//        return R.ok();
//    }

    /**
     * 删除
     */
//    @RequestMapping("/delete")
////    @RequiresPermissions("sys:buservipvalid:delete")
//    public R delete(@RequestBody Integer[] userIds){
//        bUserVipValidService.removeByIds(Arrays.asList(userIds));
//
//        return R.ok();
//    }

}
